//
//  WYOAuthController.swift
//  weibo
//
//  Created by 王玉东 on 16/4/9.
//  Copyright © 2016年 wyd. All rights reserved.
//

import UIKit
//import SVProgressHUD
import SVProgressHUD

class WYOAuthController: UIViewController {
    
    
    let webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
    
         let str = "https://api.weibo.com/oauth2/authorize?client_id=2367659728&redirect_uri=http://baidu.com"
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", NImage: nil, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", NImage: nil, target: self, action: "fullAccount")
        
        let url = NSURL(string: str)
        
        let request = NSURLRequest(URL:url!)
        
        webView.loadRequest(request)
        

        // Do any additional setup after loading the view.
    }
    
    @objc private func close() {
        
        dismissViewControllerAnimated(true, completion: nil)

    }
    
  @objc private func fullAccount() {
    
webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '13671200645', document.getElementById('passwd').value = 'wang7762997' ")
    
        //print("自动填充")
    
    }

}

extension WYOAuthController:UIWebViewDelegate {

    func webViewDidStartLoad(webView: UIWebView) {
        
        
     SVProgressHUD.show()
        
    }

    func webViewDidFinishLoad(webView: UIWebView) {
        
    SVProgressHUD.dismiss()
        
    }
    

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let str = request.URL?.absoluteString ?? ""
        
        let flag = "code="
        
        if  str.containsString(flag){
        
            let range = str.rangeOfString(flag)!
            
            let code = str.substringFromIndex(range.endIndex)
        
            print(code)
            
            //获取accesstoken
          //  loadAccessToken(code)
            
            WYUserAccaseViewModel.sharedViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                
                if !isSuccess {
                    
                    print("登录失败")
                    return
                }
                //print("登录成功")
                //跳转页面
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    NSNotificationCenter.defaultCenter().postNotificationName(WYSwitchRootViewController, object: nil)
                })
                
                
            })
            
             return false  //不授权加载页面
        }
        
        return true
    }

    
    
// private  func loadAccessToken(code:String){
//    
//    let urlString = "https://api.weibo.com/oauth2/access_token"
//        
//        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
//        
//        HMNetworkTools.sharedTools.request(HMHttpMethods.POST, urlString: urlString, parameters: parameters) { (result, error) -> () in
//           
//            if error != nil {
//             //   print(error)
//                return
//            }
//            
//            
//       self.loadUser(result!)
//
//    }
//    
//    
//}
//
//        //获取用户信息
//
//    func loadUser(result:AnyObject){
//    
//        guard let dic = result as?[String:AnyObject] else{
//            
//            print("数据错误")
//            return
//    }
//        let token = dic["access_token"]!
//        let uid = dic["uid"]!
//        let  urlstring = "https://api.weibo.com/2/users/show.json"
//        
//        let parameters = ["access_token": token, "uid": uid]
//        
//        HMNetworkTools.sharedTools.request(HMHttpMethods.GET, urlString: urlstring, parameters: parameters) { (result, error) -> () in
//            
//            
//            if error != nil {
//            
//            print("信息错误")
//                return
//            
//            }
//            
//   //         print(result)
//            
//            //合并用户信息
//            guard var userInfo = result as? [String: AnyObject] else {
//            return
//            }
//            
//            for (k , v) in dic {
//                userInfo[k] = v
//            }
//            //字典转模型(去掉没有值的数据)
//            let accout = WYUserAccase(dic: userInfo)
//            let keys = ["access_token","avatar_large","name","expires_in","uid"]
//            //获取数组
//            let dict = accout.dictionaryWithValuesForKeys(keys)
//            
//            print(dict)
//            let userDafult = NSUserDefaults.standardUserDefaults()
//            
//            userDafult.setObject(dict, forKey: userInfoKey)
//            //同步
//            userDafult.synchronize()
//        }
//        
//        
//    
//    }




}



    